package com.github.permissiondog.cancanpandroid;

import android.app.Application;
import android.content.Context;
import android.content.Intent;

import androidx.appcompat.app.AppCompatDelegate;

import com.github.permissiondog.cancanpandroid.repository.impl.LocalRepositoryImpl;
import com.github.permissiondog.cancanpandroid.util.NetUtil;
import com.squareup.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;

import java.util.HashMap;
import java.util.Map;

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
        NetUtil.PICASSO = new Picasso.Builder(this)
                .downloader(new OkHttp3Downloader(NetUtil.CLIENT))
                .build();

        setDefaultPreferences();
        loadKeepLogin();
        loadTheme();
    }

    public static MyApplication getInstance() {
        return instance;
    }

    private void setDefaultPreferences() {
        var defaultPreferences = new HashMap<String, String>();
        defaultPreferences.put("theme", "default");
        defaultPreferences.put("keepLogin", "true");

        defaultPreferences.forEach((key, value) -> {
            if (!LocalRepositoryImpl.getInstance().getPreference(key).isPresent()) {
                LocalRepositoryImpl.getInstance().setPreference(key, value);
            }
        });
    }

    private void loadKeepLogin() {
        if (!LocalRepositoryImpl.getInstance().getPreference("keepLogin").get().equals("true")) {
            LocalRepositoryImpl.getInstance().deleteAllCookies();
        }
    }

    public void loadTheme() {
        var theme = LocalRepositoryImpl.getInstance().getPreference("theme").orElse("default");
        if ("night".equals(theme)) {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);
        } else {
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        }
    }
}
